<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Shopcar;
use DB,Session;

class ShopcarController extends CommonController
{   
    // 显示购物车列表页面
    public function index()
    {
        $data = $this->putSession();
        return view('home.goods.shopcar', compact("data"));
    }
    
    // 商品详情页加入购物车
    public function addCar(Request $request)
    {
        // 验证是否登录
        if(!$this->isLogin()){
            return response()->json(['status'=>-1, 'info'=>'请先登录']);
        }
        
        $data = $request->except('_token');
        $data['user_id'] = Session::get('userData')->id;
        $data['cart_img'] = DB::table('goods')->where('id', $data['goods_id'])->pluck('goods_thumb');
        $data['cart_price'] = DB::table('goods_attr')->where('goods_id', $data['goods_id'])
                ->where('id', $data['attr_id'])
                ->pluck('attr_price');
        // 插入数据
        // 判断是否已存在该商品
        $iscar = Shopcar::where('user_id', $data['user_id'])
                ->where('attr_id', $data['attr_id'])
                ->first();
        if($iscar){
            // 存在，则只更新数量
            $res = Shopcar::where('id', $iscar->id)->increment('cart_num', $data['cart_num']);
        } else {
            $res = Shopcar::insert($data);
        }
        if(false !== $res){
            return response()->json(['status'=>1, 'info'=>'加入购物车成功']);
        } else {
            return response()->json(['status'=>0, 'info'=>'加入购物车失败']);
        }
    }
    
    //商品移除购物车
    public function deleteCar ($id)
    {
        //获取商品信息
        Shopcar::where("id", $id)->delete();
        return back();
    }
    
    // 商品增加，减少
    public function changeNum(Request $request)
    {
        // 获取商品id，用户id，执行操作
        $id = $request->get('id');
        $user_id = Session::get('userData')->id;
        $act = $request->get('act');
        
        // 获取购物车商品信息
        $car = Shopcar::find($id);
        
        // 防止非法操作
        if($user_id != $car->user_id){
            return response()->json(['status'=>0, 'info'=>'非法操作', 'num'=>$car->cart_num]);
        }
        
        // 判断操作
        if($act == 'inc'){  // increment 加
            // 判断商品数量是否超出库存
            $num = $this->getStock($car->goods_id);
            // 当前购物车数量与库存相比较
            if($num > $car->cart_num){
                $car->cart_num += 1;
                $car->save();
                $r = ['status'=>1, 'info'=>'修改成功', 'num'=>$car->cart_num];
            } else {
                $r = ['status'=>-1, 'info'=>'库存不足', 'num'=>$num];
            }
        } else {
            // 减少购物车数量
            if($car->cart_num > 1){
                $car->cart_num -= 1;
                $car->save();
                $r = ['status'=>1, 'info'=>'修改成功','num'=>$car->cart_num];
            } else {
                // 移除
                Shopcar::where('id', $id)->delete();
                $r = ['status'=>-2, 'info'=>'移除成功'];
            }
        }
        $this->putSession();
        return response()->json($r);
    }
    
    // 获取商品库存
    protected function getStock($id)
    {
        $num = DB::table('goods')->where('id', $id)
                ->where('goods_status', 1)
                ->pluck('goods_num');
        return $num;
    }
    
    // 存储session
    protected function putSession()
    {
        $user_id = Session::get('userData')->id;
        //获取购物车中的商品信息
        $data = DB::table("cart")
                ->leftJoin("goods", "cart.goods_id", "=", "goods.id")
                ->where('user_id', $user_id)
                ->select(["cart.*", "goods.goods_name"])
                ->get();
        // 存储到session中
        Session::put('shopCar'. $user_id , $data);
        return $data;
    }
}
